package com.jyw.business.obstacles.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import com.jyw.common.constant.ConfigKeyConstant;
import com.jyw.system.domain.vo.SimpleFileVo;
import com.jyw.system.service.ISysConfigService;
import com.jyw.system.service.ISysFileInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author 沈峻
 * @ClassName ProcessUtils
 * @Description TODO
 * @Date 2023/7/17 15:11
 **/
@Component
@Slf4j
public class ProcessUtils {


    @Resource
    private ISysConfigService configService;

    @Resource
    private ISysFileInfoService fileInfoService;

    /**
     * 使用sox将vaa转换成mp3解决识别问题,并上传到minio
     * @param file
     * @return
     */
    public String uploadVaa(MultipartFile file) throws IOException, InterruptedException {
        String toolPath = configService.selectConfigByKey(ConfigKeyConstant.VAA_TOOL_CONFIG);
        String cachePath = configService.selectConfigByKey(ConfigKeyConstant.CACHE_FILE_CONFIG);
        File source = new File(cachePath + File.separator + file.getOriginalFilename());
        //判断文件夹是否存在
        if(!source.getParentFile().exists()){
            source.getParentFile().mkdirs();
        }
        //保存文件
        file.transferTo(source);
        //转换文件名(转换成mp3)
        String castFile = cachePath+File.separator+file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."))+".mp3";
        //执行cmd命令
        StringBuilder builder = new StringBuilder();
        builder.append(toolPath);
        builder.append(" ");
        builder.append(source.getAbsolutePath());
        builder.append(" ");
        builder.append("-C 32.2 ");
        builder.append(castFile);
        Process exec = RuntimeUtil.exec(builder.toString());
        int i = exec.waitFor();
        if(i==0){
            log.info("@ProcessUtils:waitFor返回码:{}",i);
        }

        while (!FileUtil.exist(castFile)){
            //判断文件是否生成,如果没有生成线程睡眠等待10毫秒
            Thread.sleep(10);
        }
        //初始化大小
//        long beforeSize= new File(castFile).length();
//        log.info("@ProcessUtils:转码MP3的文件大小:{}",beforeSize);
        //上传转换后的文件
        List<SimpleFileVo> upload = fileInfoService.upload(createMultipartFile(new File(cachePath)));
        //删除服务器上的源文件与转换文件
        FileUtil.del(source);
        FileUtil.del(castFile);
        return upload.get(0).getUrl();
    }


    /**
     * File转FileItem mp3专用
     * @param file
     * @return
     */
    private MultipartFile createMultipartFile(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(file.getName(), "audio/mpeg", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }
}
